<script setup lang="ts">
import {
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqAllRoleList,
  reqRemoveRole,
  reqSetPermisstion,
} from '@/apis/acl/role'
import { useLayoutSettingStore } from '@/store/modules/setting'
import type { MenuList, Records, RoleData } from '@/types/role'
import { ElMessage, ElTree, type ElForm } from 'element-plus'
import { nextTick, onMounted, ref } from 'vue'

// 当前页码
const pageNo = ref(1)
// 每页展示多少数据
const limit = ref(5)
//分页总数据
const total = ref(10)
// 关键字
const keyWord = ref('')
//存储用户信息
const roleList = ref<Records>([])
//获取全部用户信息
const getRoleAllList = async (page = 1) => {
  pageNo.value = page
  const res = await reqAllRoleList(pageNo.value, limit.value, keyWord.value)
  if (res.code === 200) {
    //收集用户信息
    roleList.value = res.data.records
    total.value = res.data.total
  }
}
//页码大小改变
const handleSizeChange = () => {
  getRoleAllList()
}
//初始化调用
onMounted(() => {
  getRoleAllList()
})
//定义弹框组件表单
// 控制弹框组件的显示与隐藏
const dialogFormVisible = ref(false)
// 定义表单内容
const form = ref<RoleData>({
  roleName: '',
})
//定义表单规则
const rules = {
  roleName: [
    { required: true, min: 2, message: '职位名称至少两位', trigger: 'blur' },
  ],
}
//获取表单组件实例
const formRef = ref<InstanceType<typeof ElForm>>()
//添加职位
const addPermission = () => {
  //清空表单
  Object.assign(form.value, {
    roleName: '',
  })
  //移除表单校验
  nextTick(() => {
    formRef.value?.clearValidate('roleName')
  })
  //打开弹框组件
  dialogFormVisible.value = true
}
//编辑职位
const updatePermission = (row: RoleData) => {
  //移除表单校验
  nextTick(() => {
    formRef.value?.clearValidate('roleName')
  })
  //获取表单数据
  Object.assign(form.value, JSON.parse(JSON.stringify(row)))
  //打开弹框组件
  dialogFormVisible.value = true
}
//确定按钮回调事件
const confirm = async () => {
  //表单校验成功后
  await formRef.value?.validate()
  //添加和修改职位
  const res = await reqAddOrUpdateRole(form.value)
  if (res.code === 200) {
    ElMessage.success(form.value.id ? '更新成功' : '添加成功')
    //关闭弹框
    dialogFormVisible.value = false
    getRoleAllList(form.value.id ? pageNo.value : 1)
  } else {
    ElMessage.error(form.value.id ? '更新失败' : '添加失败')
    //关闭弹框
    dialogFormVisible.value = false
  }
}
//删除职位
const deletePermission = async (id: number) => {
  const res = await reqRemoveRole(id)
  if (res.code === 200) {
    ElMessage.success('删除成功')
    //关闭弹框
    dialogFormVisible.value = false
    getRoleAllList(roleList.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage.error('删除失败')
    //关闭弹框
    dialogFormVisible.value = false
  }
}
const search = () => {
  getRoleAllList()
  //清空表单
  keyWord.value = ''
}
//重置
const settingStore = useLayoutSettingStore()
const reset = () => {
  settingStore.refresh = !settingStore.refresh
}
//控制抽屉显示与隐藏
const drawer = ref(false)
//存储权限
const menuArr = ref<MenuList>([])
//存储层级的ID
const selectArr = ref<number[]>([])
//获取树形组件实例
const treeRef = ref<InstanceType<typeof ElTree>>()
const setAcl = async (row: RoleData) => {
  //打开抽屉组件
  drawer.value = true
  //收集数据
  Object.assign(form.value, row)
  //清空选中状态
  selectArr.value = []
  //获取权限数据
  const res = await reqAllMenuList(form.value.id as number)
  if (res.code === 200) {
    menuArr.value = res.data
    selectArr.value = filterSelectArr(menuArr.value, [])
    nextTick(() => {
      treeRef.value?.setCheckedKeys(selectArr.value)
    })
  }
}
//树形控件
const defaultProps = {
  children: 'children',
  label: 'name',
}
//过滤
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}
const save = async () => {
  //存储职位ID
  const roleId = form.value.id
  //获取选中节点Id
  const arr = treeRef.value!.getCheckedKeys()
  //半选中的id
  const arr1 = treeRef.value!.getHalfCheckedKeys()
  //合并数据
  const permissionId = arr.concat(arr1)
  //下方权限
  const res: any = await reqSetPermisstion(
    roleId as number,
    permissionId as number[],
  )
  if (res.code == 200) {
    //关闭抽屉
    drawer.value = false
    //用户提示
    ElMessage.success('分配权限成功')
    //重新获取数据
    getRoleAllList(pageNo.value)
  } else {
    ElMessage.error('分配权限失败')
  }
}
</script>

<template>
  <div>
    <!-- 顶部 -->
    <el-card style="height: 80px">
      <el-form :inline="true" class="form">
        <el-form-item label="职位搜索">
          <el-input placeholder="请输入职位的关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :disabled="keyWord ? false : true"
            @click="search"
          >
            搜索
          </el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 中间内容 -->
    <el-card style="margin: 10px 0">
      <el-button type="primary" icon="Plus" @click="addPermission">
        添加职位
      </el-button>
      <!-- 表格组件 -->
      <el-table :border="true" style="margin: 10px 0" :data="roleList">
        <el-table-column
          label="#"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column
          label="职位名称"
          align="center"
          prop="roleName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="280" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setAcl(row)"
            >
              分配权限
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updatePermission(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`你确认删除${row.roleName}吗？`"
              confirm-button-text="确认"
              cancel-button-text="取消"
              width="240px"
              placement="left"
              @confirm="deletePermission(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next,jumper,->,sizes,total,  "
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getRoleAllList"
      />
    </el-card>
    <!-- 弹框组件 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="form.id ? '更新职位' : '添加职位'"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        style="margin: 20px 4px"
      >
        <el-form-item label="职位名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入职位名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配角色抽屉组件 -->
    <el-drawer v-model="drawer" title="分配权限">
      <!-- 树形组件 -->
      <el-tree
        style="max-width: 600px"
        :data="menuArr"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="selectArr"
        :props="defaultProps"
        ref="treeRef"
      />
      <!-- 底部按钮 -->
      <template #footer>
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="save">确认</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
